import https from "node:https";
import { readFile } from "fs/promises";

// const baseUrl = "https://www.yuque.com/api/v2";
let config;
try {
  config = JSON.parse(await readFile("./config.json"));
} catch (err) {
  console.error(err);
}
export default config

/**
 *
 * @param {object} param0
 * @param {string} param0.path
 * @param {string} param0.method 'get'|'post'|'put'
 * @param {object} param0.options
 * @param {object} param0.postData
 * @param {function} param0.beforeSend
 * @returns
 */
export function baseApi({
  path,
  method = "GET",
  options = {},
  postData,
  beforeSend = () => {},
}) {
  return new Promise((reslove, reject) => {
    const req = https.request(
      {
        hostname: "www.yuque.com", // 请求的主机名
        path: `/api/v2${path}`, // 请求的路径
        method, // 请求方法
        headers: {
          "Content-Type": "application/json", // 请求头中的Content-Type
          "X-Auth-Token": config.token, // 请求头中的token
          "User-Agent": "User-Agent",
        },
        ...options,
      },
      (res) => {
        let data = "";
        res.on("data", function (chunk) {
          data += chunk; //接收每一块数据,chunk 是buffer,这里是有个隐式转换
        });
        res.on("error", function (err) {
          reject(err);
        });
        res.on("end", function () {
          reslove(JSON.parse(data));
        });
      }
    );
    if (postData) req.write(JSON.stringify(postData));
    beforeSend(req);
    req.end();
  });
}

// 获取用户信息
export function getUserInfo() {
  return baseApi({
    path: "/user",
  });
}

// 获取用户所有知识库
export function getAllRepos() {
  return baseApi({
    path: `/users/${config.login}/repos`,
  });
}

// 获取某一知识库的文档列表
export function getRepoDocs(namespace){
  return baseApi({
    path:`/repos/${namespace}/docs`
  })
}

// 获取文章详情
export function getDocDetail(namespace,slug){
  return baseApi({
    path:`/repos/${namespace}/docs/${slug}`
  })
}

